/**
 * 数据库模块简单封装
 * mysql 详细使用参考 https://github.com/mysqljs/mysql 模块 
 * @auth iamluodong@126.com
 */
var mysql = require('mysql');
var log = require("log4js").getLogger("db");
var API = {
    init: function (opts) {
        this.opts = opts;

        this.pool = mysql.createPool({
            connectionLimit: 10,
            host: opts.host,
            user: opts.user,
            // charset : opts.charset,
            password: opts.password,
            database: opts.db
        });
    },
    query: function (subStatement, callback) {
        var self = this;

        var _call = function (offset, length, scallback) {
            var sql = "select *  from " + subStatement + " limit " + offset + "," + length;
            log.debug(sql);
            self.execute(sql, function (err, rows) {
                if (err)
                    scallback(err)
                else
                    scallback(null, rows)
            })
        }

        self.execute("select count(*) as total from " + subStatement, function (err, result) {
            if (err)
                callback(err)
            else
                callback(null, result[0].total, _call)
        })


    },
    execute: function (sql, data, callback) { //callback(err, rows)
        var self = this;
        self.pool.query(sql, data, callback)
    },

    getConnection: function (callback) { //function(err, connection)
        //need connection.release() return to the pool
        self.pool.getConnection(callback)
    }
}

module.exports = API;